import sys
from PyQt5.QtWidgets import QSlider, QApplication, QVBoxLayout, QHBoxLayout, QWidget, QLabel
from PyQt5.QtCore import Qt

class AdvancedSignalHandling(QWidget):
    def __init__(self):
        super().__init__()
        self.setup_ui()
        self.setup_advanced_signals()
    
    def setup_ui(self):
        layout = QVBoxLayout()
        
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(0, 1000)
        self.slider.setTickPosition(QSlider.TicksBelow)
        self.slider.setTickInterval(100)
        
        self.value_label = QLabel("值: 0")
        self.action_label = QLabel("操作: 无")
        
        layout.addWidget(self.slider)
        layout.addWidget(self.value_label)
        layout.addWidget(self.action_label)
        self.setLayout(layout)
    
    def setup_advanced_signals(self):
        # 使用标志位跟踪操作状态
        self.is_dragging = False
        self.last_value = 0
        
        # 连接信号
        self.slider.sliderPressed.connect(self.start_drag)
        self.slider.sliderMoved.connect(self.during_drag)
        self.slider.sliderReleased.connect(self.end_drag)
        self.slider.valueChanged.connect(self.on_any_change)
    
    def start_drag(self):
        self.is_dragging = True
        self.action_label.setText("操作: 拖动中")
        self.last_value = self.slider.value()
    
    def during_drag(self, value):
        if self.is_dragging:
            change = value - self.last_value
            direction = "增加" if change > 0 else "减少"
            self.value_label.setText(f"值: {value} ({direction} {abs(change)})")
    
    def end_drag(self):
        self.is_dragging = False
        self.action_label.setText("操作: 完成拖动")
        # 可以在这里执行最终确认操作
        self.confirm_value(self.slider.value())
    
    def on_any_change(self, value):
        if not self.is_dragging:
            # 程序化改变或键盘操作
            self.action_label.setText("操作: 程序改变")
            self.value_label.setText(f"值: {value}")
    
    def confirm_value(self, value):
        print(f"确认最终值: {value}")
        # 执行相关业务逻辑





if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = AdvancedSignalHandling()
    window.show()
    sys.exit(app.exec_())